package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.repository.UserInfoRepository;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.AssertUtil;
import cn.wolfcode.luowowo.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

@Service
public class UserInfoServiceImp implements IUserInfoService{

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private IUserInfoRedisService redisService;

    @Override
    public UserInfo get(String id) {
        return userInfoRepository.findById(id).orElse(null);
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo user = userInfoRepository.findByPhone(phone);
        return user != null;
    }

    @Override
    public void sendVerifyCode(String phone, String smsUrl, String smsSign, String smsAppkey) {
        //产生验证码
        String code = UUID.randomUUID().toString().
                replaceAll("-", "").substring(0, 4);
        //发送验证码
        StringBuilder sb = new StringBuilder(100);
        sb.append("您好,注册的验证码是:").append(code).append("请在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内完成注册");
        System.out.println(sb.toString());//打印一下,假装已经发送

        /*String url = "https://way.jd.com/chuangxin/dxjk?mobile=" + phone + "&content=【创信】你的验证码是：" +
                sb.toString() + "，3分钟内有效！&appkey=5eeeabf6849c778cc003fa2fbe3a75c6";*/

        //sms.url=https://way.jd.com/chuangxin/dxjk?mobile={1}&content={2}你的验证码是：{3}，3分钟内有效！&appkey={4}
        //真实发送 java中发送短信
        RestTemplate restTemplate = new RestTemplate();
        //路径,返回类型,是否有参数
        String result = restTemplate.getForObject(smsUrl, String.class,phone,smsSign,sb.toString(),smsAppkey);
        String ret = result.toLowerCase();
        System.out.println(result);
        System.out.println(ret);
        if(!ret.contains("success")){
            throw new LogicException("短信发送失败");
        }

        //存储验证码
        redisService.setVerifyCode(phone,code);
    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        //判断参数是否为空
        //Assert.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"首次密码不能为空");
        AssertUtil.hasLength(rpassword,"重复密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");

        //判断密码是否一致
        AssertUtil.isEquals(password,rpassword,"两次密码不一致");

        //判断手机格式是否正确 TODO JAVA正则

        //判断验证码是否一致
        //redis的code
        String code = redisService.getVerifyCode(phone);

        if(code == null || !code.equalsIgnoreCase(verifyCode)){
            throw new LogicException("验证码失效或者不一致");
        }

        //手机号码是否唯一
        if(this.checkPhone(phone)){
            throw new LogicException("手机号码已经被注册");
        }

        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setPassword(password);//假装加密了
        userInfo.setEmail("");
        userInfo.setCity("");
        userInfo.setInfo("");
        userInfo.setLevel(1);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setState(UserInfo.STATE_NORMAL);

        //模拟系统出错

        //保存
        this.save(userInfo);

    }

    @Override
    public void save(UserInfo userInfo) {
        userInfoRepository.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {

        /*UserInfo userInfo = userInfoRepository.findByPhoneAndPassword(username,password);

        if(userInfo == null){
            throw new LogicException("账号或者密码错误");
        }*/

        //查询用户
        UserInfo userInfo = userInfoRepository.findByPhone(username);

        if(userInfo == null || !password.equals(userInfo.getPassword())){
            throw new LogicException("账号或者密码错误");
        }

        //userInfo.setPassword("null");

        return userInfo;
    }
}

